import Tab from "../../components/Tab";
import {SideBar} from "antd-mobile";
import './index.scss'
import LiteratureList from "../../components/LiteratureList";
import Header from "../../components/Header";
import {dictLiteratureList, literatureList} from "../../api/api";
import {useEffect, useState, useTransition} from "react";
import RequestLoading from "../../components/RequestLoading";


const Literature = () => {
    const [loading, sartTransition] = useTransition();
    // tab栏
    const [tabs, setTabs] = useState<Array<{ key: string, title: string }>>([]);
    // 选择key
    const [activeKey, setActiveKey] = useState<string>('');
    // 请求数据
    const [data, setData] = useState<Array<{ id: string, name: string, cover_url: string }>>([]);
    // 请求字典
    const getDict = () => {
        sartTransition(() => {
            dictLiteratureList().then(r => {
                let tabs = r.map((v: { id: string, name: string }, index: number) => {
                    if (index === 0) {
                        setActiveKey(v.id)
                    }
                    return {
                        key: v.id,
                        title: v.name
                    }
                });
                setTabs(tabs);
            });
        })
    };

    // 文献数据
    const getData = () => {
        literatureList(activeKey).then(r => {
            const data = r.map((v: { id: string, name: string, cover: { path: string } }) => {
                return {
                    ...v,
                    cover_url: v.cover.path
                }
            });
            setData(data);
        })
    }

    useEffect(() => {
        getDict();
    }, []);


    useEffect(() => {
        if (activeKey) {
            getData();
        }
    }, [activeKey])

    return (
        <div className="literature-box">
            <div>
                <SideBar activeKey={activeKey} onChange={(v: string) => setActiveKey(v)}>
                    {
                        tabs.map(v => {
                            return (
                                <SideBar.Item key={v.key} title={v.title}/>
                            )
                        })
                    }
                </SideBar>
            </div>
            <div>
                {
                    loading ? <RequestLoading/> : <LiteratureList data={data}/>
                }
            </div>
            {/*右侧tab*/}
            <Tab/>
            {/*头部*/}
            <Header back={null} title="文献"/>
        </div>
    )
}

export default Literature;